//
//  WJHomeViewController.m
//  weibo
//
//  Created by 王俊 on 15/12/20.
//  Copyright © 2015年 王俊. All rights reserved.
//

#import "WJHomeViewController.h"
#import "UIBarButtonItem+WJUIBarButtonItemExt.h"
#import "WJDrawDownView.h"
#import "WJOAuthController.h"
#import "WJAccount.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "WJStatus.h"
#import "WJUser.h"
#import "WJPhoto.h"
#import "WJStatus.h"
#import "MJExtension.h"
#import "WJTableFooterView.h"


#define ReuseID @"WJReuse"


@interface WJHomeViewController()
@property(nonatomic,strong) WJAccount  *account;
@property(nonatomic,strong) NSMutableArray  *statuses;
@property(nonatomic,strong) UIRefreshControl  *refreshControl;
@property(nonatomic,strong) WJTableFooterView  *footerView;
@end
@implementation WJHomeViewController

#pragma mark -视图生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpUserInfo];
    [self setUpViews];
    [self setUpRefresh];
    [self updateStatuses];
}

- (void)viewWillAppear:(BOOL)animated
{
    //获取沙盒中的数据
    /*
     
     NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
     WJLog(@"%@",docPath);
     NSString *accountPath = [docPath stringByAppendingPathComponent:@"account.data"];
     
     */

    if (!_account) {
        WJOAuthController *vc = [[WJOAuthController alloc]init];
        [self.navigationController pushViewController:vc animated:true];
    }
}
# pragma mark -初始化view界面
- (void)setUpViews
{

    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"navigationbar_friendsearch"] highlightedImage:[UIImage imageNamed:@"navigationbar_friendsearch_highlighted"] target:self action:@selector(friendAdd)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"navigationbar_pop"] highlightedImage:[UIImage imageNamed:@"navigationbar_pop_highlighted"] target:self action:@selector(friendSearch)];
    UIButton *titleButton = [[UIButton alloc]init];
    titleButton.height = 30;
    titleButton.width = 150;
    [titleButton setTitle:@"首页" forState:UIControlStateNormal];
    [titleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [titleButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0,20)];
    [titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    [titleButton setImageEdgeInsets:UIEdgeInsetsMake(0, 90, 0, 0)];
    self.navigationItem.titleView = titleButton;
    [titleButton addTarget:self action:@selector(titleButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.footerView = [[WJTableFooterView alloc]initFooterView];
    self.table.tableFooterView = self.footerView;
    self.footerView.hidden = true;
    
    

//    [self.table setDataSource:self];
//    [self.table setDelegate:self];
}
#pragma mark -设置下拉菜单
- (void)setUpRefresh
{
    self.refreshControl = [[UIRefreshControl alloc]init];
    [self.table addSubview:_refreshControl];
    [self.refreshControl addTarget:self action:@selector(refreshControlClicked) forControlEvents:UIControlEventValueChanged];
    [self.refreshControl beginRefreshing];
}
#pragma mark -下拉刷新触发事件
- (void)refreshControlClicked
{
    WJLog(@"refresh!")  ;
    [self updateStatuses];
        
    
}
#pragma mark -设置用户信息
- (void)setUpUserInfo
{
    _account = [WJAccount accountFromSandBox];
    self.table.dataSource = self;
    self.table.delegate = self;
    if (_account) {
        AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]init];
        
        NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
        parameters[@"access_token"] = [_account valueForKey:@"access_token"];
        parameters[@"uid"] = [_account valueForKey:@"uid"];
        
        
        NSString *urlString = @"https://api.weibo.com/2/users/show.json";
        
        [manager GET:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSString *iconUrlString = responseObject[@"profile_image_url"];
            if (_account.profile_image_url != iconUrlString) {
                _account.profile_image_url = iconUrlString;
                [_account save];
            }


            
            //WJLog(@"respose: %@",responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            WJLog(@"error:%@",error);
        }];
    }else{
        WJOAuthController *vc = [[WJOAuthController alloc]init];
        [self.navigationController pushViewController:vc animated:true];
    }
    
}

#pragma mark -显示以刷新数提醒
- (void)showNewStatusWithCount:(NSUInteger)count
{
    UILabel *label = [[UILabel alloc]init];
    label.width = SCNWDTH;
    label.height = 30;
    label.x = 0;
    label.y = 64 - label.height;
    label.backgroundColor = [UIColor redColor];
    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];

    label.text = ((count > 0) ? [NSString stringWithFormat:@"更新了%tu条微博数据...",count]:@"没有更新到新微博...");
    label.textAlignment = NSTextAlignmentCenter;
    [UIView animateWithDuration:1 animations:^{
        label.transform = CGAffineTransformMakeTranslation(0, label.height);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:1 delay:1 options:0 animations:^{
            label.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [label removeFromSuperview];
        }];
    }];
}

- (void)updateStatuses
{
    if (_account) {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"access_token"] = _account.access_token;
        NSString *firstSinceId = [[self.statuses firstObject] idstr];
        if (firstSinceId) {
            param[@"since_id"] = firstSinceId;
        }
        
        //NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/2/statuses/friends_timeline.json"];
        [manager GET:@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:(param) progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //WJLog(@"success: %@",responseObject);
            NSArray *newStatuses = responseObject[@"statuses"];
            NSArray *models = [WJStatus mj_objectArrayWithKeyValuesArray:newStatuses];
            [self showNewStatusWithCount:models.count];
            NSRange range = NSMakeRange(0, models.count);
            NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:range];
            
            [self.statuses insertObjects:models atIndexes:set];
            //[self.statuses addObjectsFromArray:models];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.table reloadData];
                
                [self.refreshControl endRefreshing];
                
                
            });
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            WJLog(@"failed: %@",error);
        }];
        
    
        
    }
}
- (void)getMoreStatuses
{
    if (_account) {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"access_token"] = _account.access_token;
        NSString *lastSinceId = [[self.statuses lastObject] idstr];
        if (lastSinceId) {
            param[@"max_id"] = lastSinceId;
        }
        
        //NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/2/statuses/friends_timeline.json"];
        [manager GET:@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:(param) progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //WJLog(@"success: %@",responseObject);
            NSArray *newStatuses = responseObject[@"statuses"];
            NSArray *models = [WJStatus mj_objectArrayWithKeyValuesArray:newStatuses];
            [self.statuses addObjectsFromArray:models];
            //[self.statuses addObjectsFromArray:models];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.table reloadData];
                
                [self.footerView dismiss];
                
                
            });
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            WJLog(@"failed: %@",error);
        }];
        
    }
}

#pragma mark -tableView Delegate监听

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.statuses.count != 0){
    if (self.table.contentOffset.y > (self.table.contentSize.height + self.table.contentInset.bottom - self.table.height + 20) && self.footerView.hidden) {
        WJLog(@"需要更新了！");
        //WJLog(@"before : %@",self.footerView.hidden);
        self.footerView.hidden = false;
        
        [self getMoreStatuses];
        
        
    }
    }

}

#pragma mark -监听点击事件

- (void)friendAdd
{
    WJLog(@"add friend");
}

- (void)friendSearch
{
    WJOAuthController *vc = [[WJOAuthController alloc]init];
    [self.navigationController pushViewController:vc animated:true];
}

- (void)titleButtonClicked:(UIButton*)sender
{
    WJDrawDownView *drawView = [[WJDrawDownView alloc]init];
    drawView.delegate = self;
    drawView.contentView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 100, 144)];
    [drawView show:sender];
    UIButton *btn = (UIButton*)self.navigationItem.titleView;
    [btn setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateNormal];
}

- (void)WJDrawDownViewDismiss:(WJDrawDownView*) menu
{
    UIButton *btn = (UIButton*)self.navigationItem.titleView;
    [btn setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    
}

#pragma mark -acccount的懒加载
-(WJAccount*)account
{
    if (!_account) {
        _account = [WJAccount accountFromSandBox];
    }
    return _account;
}


#pragma mark -tableView的dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return  _statuses.count;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ReuseID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ReuseID];
    }
    //WJLog(@"%@",_statuses[indexPath.row][@"created_at"]);
    WJStatus *status = _statuses[indexPath.row];
    WJUser *user = status.user;
    NSURL *url = [NSURL URLWithString:user.profile_image_url];
    cell.textLabel.text = [NSString stringWithFormat:@"%@",user.name];
#pragma mark -测试显示时间
    

    //cell.detailTextLabel.text = status.text;
    //cell.detailTextLabel.text = status.source;
    cell.detailTextLabel.text = status.created_at;
    WJLog(@"%@",status.source);
    
    [cell.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"avatar_default_big"]];
    return cell;
}



- (NSMutableArray*)statuses
{
    if (!_statuses) {
        _statuses = [[NSMutableArray alloc]init];
    }
    return _statuses;
}




@end



